<?php

namespace app\common\model;

use app\common\model\coupon\Log;
use app\common\model\order\Goods;
use app\common\model\user\Address;
use think\Model;
use traits\model\SoftDelete;

class Order extends Model
{

    use SoftDelete;



    // 表名
    protected $name = 'order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'paytime_text',
        'status_text',
        'canceltime_text',
        'taketime_text',
        'create_time_text',
        'is_settlement_text'
    ];
    public function user()
    {
        return $this->belongsTo('app\common\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function goods()
    {
        return $this->hasMany('app\common\model\order\Goods', 'order_id', 'id');
    }

    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1'), '2' => __('Status 2'), '3' => __('Status 4')];
    }

    public function getIsSettlementList()
    {
        return ['0' => __('Is_settlement 0'), '1' => __('Is_settlement 1')];
    }

    public function getCreatetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }
    public function getPaytimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['paytime']) ? $data['paytime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getCanceltimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['canceltime']) ? $data['canceltime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getTaketimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['taketime']) ? $data['taketime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }




    public function getIsSettlementTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['is_settlement']) ? $data['is_settlement'] : '');
        $list = $this->getIsSettlementList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    protected function setPaytimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setCanceltimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setTaketimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }
    public function yuOrder($goods, $pay_type, $integral, $address_id, $uid, $coupon_id = 0)
    {
        $user = User::get($uid);
        if ($user['group_id'] == 1) {
            $pay_money = $data['total_money'] = array_sum(array_column($goods, 'money'));
        } else {
            $pay_money = $data['total_money'] = array_sum(array_column($goods, 'inside_price'));
        }
        $data['total_integral'] = array_sum(array_column($goods, 'total_integral'));
        $data['discount'] =  0;
        $data['total'] = array_sum(array_column($goods, 'num'));
        $addressInfo = [];
        $data['discount'] = $data['point_discount'] = $data['coupon_discount'] = 0;
        if (isset($integral) && !empty($integral)) {
            $data['point_discount'] = bcdiv($integral, config('site.integral_ratio'), 2);
            $data['discount'] +=  $data['point_discount'];
            $pay_money -= $data['point_discount'];
            $pay_money = $pay_money >= 0 ?? 0;
        }
        $data['integral'] = $integral;
        $data['pay_type'] = $pay_type;
        if (isset($address_id) && !empty($address_id)) {
            $addressInfo = Address::get($address_id);
            $data['addressInfo'] = $addressInfo;
            $data['address_id']  = $address_id;
        } else {
            $addressInfo = Address::getDefaultAddress($uid);
            if ($addressInfo) {
                $data['addressInfo'] = $addressInfo;
                $data['address_id']  = $addressInfo['id'];
            }
        }
        $log = new Log();
        if (isset($coupon_id) && $coupon_id) {
            $coupon = Log::get($coupon_id);
            $data['coupon_discount'] =  Log::useCoupon($pay_money, $coupon_id, $uid);
            $data['discount'] += $data['coupon_discount'];
            $data['coupon_id'] = $coupon_id;
            $pay_money -= $data['coupon_discount'];
            $pay_money = $pay_money >= 0 ?? 0;
        } else {
            $coupon = $log->useMaxCoupon($pay_money, $uid);
            if ($coupon) {
                $data['coupon_discount'] = Log::useCoupon($pay_money, $coupon['id'], $uid);
            }
            $data['discount'] +=  $data['coupon_discount'];
        }
        $data['express_charge'] = config('site.express_charge');
        $data['pay_money'] = bcadd($pay_money, $data['express_charge'], 2);

        $data['goodsList'] = $goods;

        return $data;
    }
    public  function addData($data,  $uid)
    {
        $list = $data['goodsList'];
        $user = User::get($uid);
        $addressInfo = [];
        if ($data['addressInfo']) {
            $addressInfo = $data['addressInfo'];
        }
        $array = [
            'user_id' => $uid,
            'total_money' =>  $data['total_money'] - $data['discount'],
            'total' =>  $data['total'],
            'pay_money' =>  $data['pay_money'] - $data['discount'],
            'discount' =>  $data['discount'],
            'integral' =>  $data['total_integral'],
            'point_discount' =>  $data['point_discount'] ?? 0,
            'coupon_discount' =>  $data['coupon_discount'] ?? 0,
            'express_charge' =>  $data['express_charge'] ?? 0,
            'sn' => sn('order', 'sn', 'GO'),
            'address_id' => $data['address_id'],
            'coupon_id' => $data['coupon_id'] ?? 0,
            'pay_type' => $data['pay_type'],
            'consignee' => $addressInfo['contact'] ?? '',
            'phone' => $addressInfo['telephone'] ?? '',
            'address' => $addressInfo['province'] . '/' . $addressInfo['city'] . '/' . $addressInfo['district'] . '/' . $addressInfo['address'],
        ];
        $res = $this->allowField(true)->save($array);
        if ($res) {
            foreach ($list as $vo) {
                if ($user->group_id == 2) {
                    $price = $vo['item']['inside_price'];
                } else {
                    $price = $vo['item']['price'];
                }
                $info = [
                    'order_id' => $this->id,
                    'goods_id' => $vo['goods_id'],
                    'goods_num' => $vo['num'],
                    'goods_name' => $vo['goods']['title'],
                    'item_name' => $vo['item']['title'],
                    'goods_price' => $price,
                    'total_price' => $price * $vo['num'],
                    'image' => $vo['goods']['image'],
                ];
                $infos = new Goods();
                $infos->isUpdate(false)->save($info);
            }
        }
        return $this->id;
    }
}
